package mysql

import (
	"gorm.io/gorm"
	"shuqi-novel/userrpc/userrpc"
)

type Books struct {
	gorm.Model
	UserId   int64  `gorm:"type:int(11);not null;comment:用户id"`
	Title    string `gorm:"type:varchar(30);not null;comment:小说标题"`
	Comment  string `gorm:"type:varchar(50);not null;comment:小说简介"`
	BookType string `gorm:"type:varchar(20);not null;comment:小说分类"`
}

func (b *Books) BookAdd(db *gorm.DB) error {
	return db.Debug().Create(b).Error
}

func (b *Books) PerfectBook(db *gorm.DB) error {
	return db.Debug().Updates(b).Error
}

func (b *Books) FindBook(db *gorm.DB, id int64) error {
	return db.Debug().Where("id =? ", id).First(b).Error
}

/*
SELECT

	books.id book_id,
	books.title,
	books.COMMENT comment,
	books.book_type

FROM

	books
	LEFT JOIN users ON books.user_id = users.id

WHERE books.user_id=2
*/
func BookList(db *gorm.DB, in *userrpc.BookListRequest) []*userrpc.BookList {
	var list []*userrpc.BookList
	db.Debug().Model(&Books{}).
		Select(
			"books.id book_id",
			"books.title",
			"books.COMMENT comment",
			"books.book_type",
		).
		Joins("LEFT JOIN users ON books.user_id = users.id").
		Scopes(Paginate(int(in.Page), int(in.Size))).
		Where("books.user_id=?", in.UserId).Find(&list)
	return list
}
